package cn.my.framework.config.shiro;

import cn.my.framework.common.entity.Permission;
import cn.my.framework.common.entity.Role;
import cn.my.framework.common.entity.User;
import cn.my.framework.common.service.UserPermService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by zhangl_lc on 2017/7/11.
 */
@Component
public class MyShiroRealm extends AuthorizingRealm {

    Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

    @Autowired
    UserPermService permService;

    @Override
    public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo auths = new SimpleAuthorizationInfo();
        List<Role> roles = permService.listRoles(username);
        roles.forEach(r ->{
            auths.addRole(r.getCode());
        });
        List<Permission> perms = permService.listPermsByUser(username);
        perms.forEach(p ->{
            auths.addStringPermission(p.getCode());
        });
        return auths;
    }

    @Override
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken)token;
        String username = upToken.getUsername();
        User user = permService.findUser(username);
        logger.debug(">>>>> the login user is :{}",user);
        if(user == null){
            throw new UnknownAccountException("用户不存在");
        }
        AuthenticationInfo authInfo = new SimpleAuthenticationInfo(user.getCode(),user.getPassword(),getName());
        return authInfo;
    }
}
